package com.excel.operations;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelUtils {
	
	public static Workbook getWorkBook(String filePath) throws FileNotFoundException, IOException{
		Workbook workbook = null;
		if("xlsx".equals(getFileExtention(filePath))){
			workbook = new XSSFWorkbook(new FileInputStream(filePath));
		}else if("xls".equals(getFileExtention(filePath))){
			workbook = new HSSFWorkbook(new FileInputStream(filePath));
		}else{
			System.out.println("The file dont have any xls or xlsx extention. Verify the file name and its extention." + filePath);
		}
		return workbook;
	}
	
	public static Workbook getNewWorkBook(String filePath){
		Workbook workbook = null;
		if("xlsx".equals(getFileExtention(filePath))){
			workbook = new XSSFWorkbook();
		}else if("xls".equals(getFileExtention(filePath))){
			workbook = new HSSFWorkbook();
		}else{
			System.out.println("The file dont have any xls or xlsx extention. Verify the file name and its extention." + filePath);
		}
		return workbook;
	}
	
	public static String getFileExtention(String filePath){
		String fileExtention = "";
		int i = filePath.lastIndexOf('.');
		if (i >= 0) {
		    fileExtention = filePath.substring(i+1);
		    fileExtention = fileExtention.toLowerCase();
		}
		return fileExtention;
	}
}
